package com.admin.action;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.admin.bean.AdminUserBean;
import com.admin.bean.CompanyBean;
import com.admin.service.AdminUserService;
import com.admin.util.BaseUtil;
import com.admin.util.BillingUtil;
import com.admin.util.PageBean;

/**
 * @Title: AdminUserAction.java
 * @Package com.admin.action
 * @Description:
 * @author Jason
 * @date 2010-12-15 上午10:41:39
 * @version
 */

@Controller
@RequestMapping("/adminUser")
public class AdminUserAction {

	private static Logger log = Logger.getLogger(AdminUserAction.class);

	@Autowired
	private AdminUserService adminUserService;

	/**
	 * @Title: list
	 * @Description:分页显示用户列表
	 * @param request
	 * @return
	 * @throws
	 */
	@RequestMapping()
	public String list(HttpServletRequest request,HttpServletResponse response) {
		AdminUserBean user = (AdminUserBean) request.getSession().getAttribute("adminUser");
		if(user.getPower()==1){
			
			StringBuilder condition = new StringBuilder(" 1=1 ");
			
			String cpname = request.getParameter("cpname");
			String bussiness = request.getParameter("bussiness");
			
			if(cpname!=null&&cpname.length()>0) {
				condition.append(" and cpname like '%");
				condition.append(cpname);
				condition.append("%' ");
			}
			
			if(bussiness!=null&&bussiness.length()>0) {
				condition.append(" and bussiness like '%");
				condition.append(bussiness);  
				condition.append("%' ");
			}
			
			List<AdminUserBean> userList = adminUserService.findCp(condition.toString());
			int totalCount = userList.size();
			
			
			
			int currentPage = BaseUtil.stringToInt(request.getParameter("currentPage"), 1);
			PageBean<AdminUserBean> page = new PageBean<AdminUserBean>(totalCount, currentPage);
			
			page.setResult(BillingUtil.getPageList(page.getCurrentPage(), page.getPageSize(), userList));
			page.setUrl("?1=1");
			request.setAttribute("pageBean", page);
			return "adminUserList";
		}else{
			StringBuffer html = new StringBuffer();
			html.append("<script>");
			html.append("alert('你没有该权限查看！');");
			html.append("history.go(-1);");
			html.append("</script>");
			BaseUtil.responseWrite(response, html);
			return null;
		}
	}
	
	@RequestMapping("adminList")
	public String adminList(HttpServletRequest request,HttpServletResponse response) {
		AdminUserBean user = (AdminUserBean) request.getSession().getAttribute("adminUser");
		if(user.getPower()==1){
			List<AdminUserBean> userList = adminUserService.findAll(0,0);
			int totalCount = userList.size();
			int currentPage = BaseUtil.stringToInt(request.getParameter("currentPage"), 1);
			PageBean<AdminUserBean> page = new PageBean<AdminUserBean>(totalCount, currentPage);
			//List<AdminUserBean> userList = adminUserService.findAll(page.getStart(), page.getPageSize());
			page.setResult(BillingUtil.getPageList(page.getCurrentPage(), page.getPageSize(), userList));
			page.setUrl("?1=1");
			request.setAttribute("pageBean", page);
			return "adminList";
		}else{
			StringBuffer html = new StringBuffer();
			html.append("<script>");
			html.append("alert('你没有该权限查看！');");
			html.append("history.go(-1);");
			html.append("</script>");
			BaseUtil.responseWrite(response, html);
			return null;
		}
	}

	@RequestMapping("/add")
	public String add(HttpServletRequest request,HttpServletResponse response) throws IOException{
		//log.info("登出==>");
		System.out.println("company add");
		String username = request.getParameter("username");
		String pwd = request.getParameter("pwd");
		int power = BaseUtil.stringToInt(request.getParameter("power"));
		String cpname = request.getParameter("cpname");
		String cpmemo = request.getParameter("cpmemo");
		int cppercent = BaseUtil.stringToInt(request.getParameter("cppercent"));
		int cpstatus = BaseUtil.stringToInt(request.getParameter("cpstatus"));
		
		String bussiness = request.getParameter("bussiness");
		String cpercent = request.getParameter("cpercent");
		String cpcheck = request.getParameter("cpcheck");
		String spchannel = request.getParameter("spchannel");
		String mourl = request.getParameter("mourl");
		String mturl = request.getParameter("mturl");
//		private int bussiness;		//业务线
//		private int cpercent;		//分成比率
//		private String cpcheck;		//结算周期
//		private String spchannel;	//合作的SP渠道
//		private int cstatus;			//状态
		AdminUserBean bean = new AdminUserBean();
		
		bean.setUsername(username);
		bean.setPwd(pwd);
		bean.setPower(power);
		bean.setCpname(cpname);
		bean.setCpmemo(cpmemo);
		bean.setCppercent(cppercent);
		bean.setCpstatus(cpstatus);
		bean.setBussiness(bussiness);
		bean.setCpercent(cpercent);
		bean.setCpcheck(cpcheck);
		bean.setSpchannel(spchannel);
		bean.setMourl(mourl==null?"":mourl);
		bean.setMourl(mturl==null?"":mturl);
		System.out.println("company add2");
		boolean flag = adminUserService.addAdminUser(bean);
		System.out.println("company add3");
		response.setContentType("text/html");
		response.getWriter().print(flag?"1":"0");
		return null;
	}

	/**
	 * @Title: login
	 * @Description:用户登陆
	 * @param userName
	 * @param userPwd
	 * @return
	 * @throws
	 */
	@RequestMapping("/login")
	public void login(HttpServletRequest request,HttpServletResponse response) {
		log.info("用户登录==>");
		String userName = request.getParameter("userName");
		String userPwd  = request.getParameter("userPwd");
		log.info("userName:" + userName + ",userPwd=" + userPwd);
		Map<String,Object> map =  adminUserService.login(userName, userPwd);
		int flag = (Integer)map.get("flag");
		if (flag == 0) {
			log.info("登录成功！");
			AdminUserBean adminUser = (AdminUserBean) map.get("user");
			request.getSession().setAttribute("adminUser", adminUser);
		} else {
			log.error("登录失败!");
		}
		BaseUtil.responseWrite(response, flag);
	}

	@RequestMapping("/updatePwdUI")
	public String updatePwdUI(){
		return "updatePwd";
	}
	
	/**
	  * @Title: updatePwd
	  * @Description: 修改用户密码
	  * @param oldPwd
	  * @param newPwd
	  * @param request
	  * @return
	  * @throws
	 */
	@RequestMapping("/updatePwd")
	public void updatePwd(HttpServletRequest request,HttpServletResponse response) {
		log.info("用户修改密码==>");
		String oldPwd = request.getParameter("oldPwd");
		String newPwd = request.getParameter("newPwd");
		log.info("oldPwd="+oldPwd+",newPwd="+newPwd);
		int result = 0;
		AdminUserBean adminUser = (AdminUserBean) request.getSession().getAttribute("adminUser");
		if(!oldPwd.equals(adminUser.getPwd())){
			log.error("用户旧密码不正确，修改失败！");
			result = 2;
		}else if(adminUserService.updateUserPwd(adminUser.getId(), newPwd)){
			log.info("修改密码成功!");
			request.getSession().removeAttribute("adminUser");
			request.getSession().invalidate();
			result = 0;
		}else{
			log.error("修改密码失败!");
			result = 1;
		}
		BaseUtil.responseWrite(response, result);
	}
	
	/**
	  * @Title: updateStatus
	  * @Description:修改用户状态 
	  * @param userId
	  * @param status
	  * @return
	  * @throws
	 */
	@RequestMapping("/updateStatus")
	public void updateStatus(HttpServletRequest request,HttpServletResponse response){
		log.info("修改用户状态==>");
		int userId = BaseUtil.stringToInt(request.getParameter("userId"));
		int status = BaseUtil.stringToInt(request.getParameter("status"));
		log.info("userId="+userId+",status="+status);
		int result = 0;
		if(adminUserService.updateUserStatus(userId, status)){
			log.info("修改用户状态成功!");
		}else{
			log.error("修改用户状态失败！");
			result = 1;
		}
		BaseUtil.responseWrite(response, result);
	}
	
	/**
	  * @Title: logout
	  * @Description:登出 
	  * @param request
	  * @param responsecccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
	  * @throws IOException
	  * @throws
	 */
	@RequestMapping("/logout")
	public void logout(HttpServletRequest request,HttpServletResponse response) throws IOException{
		log.info("登出==>");
		request.getSession().removeAttribute("adminUser");
		request.getSession().invalidate();
		response.sendRedirect(request.getContextPath()+"/index.jsp");
	}
	
	@RequestMapping(value="/view/{userId}",method=RequestMethod.GET)
	public String view(@PathVariable int userId,HttpServletRequest request){
		AdminUserBean bean = adminUserService.findById(userId);
		
		request.setAttribute("bean", bean);
		return "adminUserView";
	}
	
	
	@RequestMapping("/modify")
	public ModelAndView modify(HttpServletRequest request,HttpServletResponse response) throws IOException{
		System.out.println("modify 1");
		AdminUserBean bean = new AdminUserBean();
		int id = BaseUtil.stringToInt(request.getParameter("id"));
		int power = BaseUtil.stringToInt(request.getParameter("power"));
		String cpname = request.getParameter("cpname");
		String cpmemo = request.getParameter("cpmemo");
		int cppercent = BaseUtil.stringToInt(request.getParameter("cppercent"));
		int cpstatus = BaseUtil.stringToInt(request.getParameter("cpstatus"));
		
		String bussiness = request.getParameter("bussiness");
		String cpercent = request.getParameter("cpercent");
		String cpcheck = request.getParameter("cpcheck");
		String spchannel = request.getParameter("spchannel");
		String mourl = request.getParameter("mourl");
		String mturl = request.getParameter("mturl");
		
		bean.setId(id);
		bean.setPower(power);
		bean.setCpname(cpname);
		bean.setCpmemo(cpmemo);
		bean.setCppercent(cppercent);
		bean.setCpstatus(cpstatus);
		bean.setBussiness(bussiness);
		bean.setCpercent(cpercent);
		bean.setCpcheck(cpcheck);
		bean.setSpchannel(spchannel);
		bean.setMourl(mourl==null?"":mourl);
		bean.setMturl(mturl==null?"":mturl);
//		company.setCompanyId(companyId);
//		company.setCompanyName(request.getParameter("companyName"));
//		company.setCompanyMemo(request.getParameter("companyMemo"));
//		company.setCompanyAddr(request.getParameter("companyAddr"));
//		company.setCompanyTel(request.getParameter("companyTel"));
//		company.setCompanyFax(request.getParameter("companyFax"));
//		company.setCompanyHome(request.getParameter("companyHome"));
//		company.setBussiness(request.getParameter("bussiness"));
//		company.setSppercent(BaseUtil.stringToInt(request.getParameter("percent")));
//		company.setSpcheck(request.getParameter("check"));
//		company.setCommandMemo(request.getParameter("commandMemo"));
//		company.setSpstatus(BaseUtil.stringToInt(request.getParameter("status")));
		System.out.println("modify 2");
		int flag = adminUserService.updateAdminUser(bean);
		System.out.println("modify 3");
		response.setContentType("text/html");
		response.getWriter().print(flag);
		return null;
	}
}